import request from '@/utils/request'

/**
 * 获取漏洞列表
 * @param {Object} params 查询参数
 * @returns {Promise} promise
 */
export function listVulnerabilities(params) {
  return request({
    url: '/vulnerabilities',
    method: 'get',
    params
  })
}

/**
 * 获取漏洞详情
 * @param {String} id 漏洞ID
 * @returns {Promise} promise
 */
export function getVulnerability(id) {
  return request({
    url: `/vulnerabilities/${id}`,
    method: 'get'
  })
}

/**
 * 创建漏洞
 * @param {Object} data 漏洞数据
 * @returns {Promise} promise
 */
export function createVulnerability(data) {
  return request({
    url: '/vulnerabilities',
    method: 'post',
    data
  })
}

/**
 * 更新漏洞
 * @param {String} id 漏洞ID
 * @param {Object} data 更新数据
 * @returns {Promise} promise
 */
export function updateVulnerability(id, data) {
  return request({
    url: `/vulnerabilities/${id}`,
    method: 'put',
    data
  })
}

/**
 * 删除漏洞
 * @param {String} id 漏洞ID
 * @returns {Promise} promise
 */
export function deleteVulnerability(id) {
  return request({
    url: `/vulnerabilities/${id}`,
    method: 'delete'
  })
}

/**
 * 批量导入漏洞
 * @param {FormData} formData 包含文件的表单数据
 * @returns {Promise} promise
 */
export function batchImportVulnerabilities(formData) {
  console.log('调用批量导入API, 表单数据:', formData.get('file') ? '文件已附加' : '没有文件')
  return request({
    url: '/vulnerabilities/import',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    timeout: 30000, // 延长超时时间到30秒
    onUploadProgress: progressEvent => {
      console.log('上传进度:', Math.round((progressEvent.loaded / progressEvent.total) * 100) + '%')
    }
  })
}

/**
 * 获取漏洞的AI风险评估
 * @param {Object} data 含漏洞信息和上下文的数据
 * @returns {Promise} promise
 */
export function getVulnRiskAssessment(data) {
  console.log('[调试-API] 收到风险评估请求数据:', JSON.stringify(data, null, 2))
  
  // 精简请求数据结构，确保符合后端期望格式
  const requestData = {
    id: String(data.id || 'test-id'), // 强制转换为字符串
    title: data.title || '测试标题',
    cve_id: data.cve_id || '',
    original_severity: data.original_severity || 'medium',
    description: data.description || '测试描述',
    assets: []
  }
  
  // 只有当数组存在且非空时才添加资产数据
  if (Array.isArray(data.assets) && data.assets.length > 0) {
    requestData.assets = data.assets.map(asset => ({
      id: String(asset.id || ''), // 强制转换为字符串
      name: asset.name || '',
      type: asset.type || '',
      importance: asset.importance || '一般'
    }))
  }
  
  console.log('[调试-API] 精简后的请求数据:', JSON.stringify(requestData, null, 2))
  console.log('[调试-API] ID类型:', typeof requestData.id)
  
  // 使用与测试脚本一致的请求方式
  return request({
    url: '/ai/risk-assessment',
    method: 'post',
    data: requestData,
    timeout: 30000, // 30秒超时
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  })
}

/**
 * 使用原生fetch直接调用AI风险评估API
 * @param {Object} data 含漏洞信息和上下文的数据
 * @param {String} token 认证token
 * @returns {Promise} promise
 */
export function directFetchRiskAssessment(data, token) {
  console.log('[直接调用] 开始请求，Token:', token ? '已设置' : '未设置')
  
  // 构造请求数据
  const requestData = {
    id: String(data.id || 'test-id'), // 强制转换为字符串
    title: data.title || '测试标题',
    cve_id: data.cve_id || '',
    original_severity: data.original_severity || 'medium',
    description: data.description || '测试描述',
    assets: []
  }
  
  // 发送请求
  return fetch('/api/v1/ai/risk-assessment', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token ? `Bearer ${token}` : ''
    },
    body: JSON.stringify(requestData)
  })
  .then(response => {
    console.log('[直接调用] 状态:', response.status)
    
    // 克隆响应以便多次读取
    const clonedResponse = response.clone()
    
    // 返回响应文本以便调试
    return clonedResponse.text().then(text => {
      console.log('[直接调用] 响应:', text)
      
      // 尝试解析JSON
      try {
        const data = JSON.parse(text)
        return {
          ok: response.ok,
          status: response.status,
          data: data
        }
      } catch (e) {
        return {
          ok: response.ok,
          status: response.status,
          text: text,
          error: '无法解析JSON'
        }
      }
    })
  })
  .catch(error => {
    console.error('[直接调用] 错误:', error)
    throw error
  })
}

/**
 * 批量删除漏洞
 * @param {Array} ids 漏洞ID数组
 * @returns {Promise} promise
 */
export function batchDeleteVulnerabilities(ids) {
  console.log('调用批量删除API, 参数:', { ids })
  return request({
    url: '/vulnerabilities/batch-delete',
    method: 'post',
    data: { ids },
    headers: {
      'Content-Type': 'application/json'
    },
    timeout: 10000, // 10秒超时
    validateStatus: function (status) {
      // 扩大接受的状态码范围，便于调试
      return status >= 200 && status < 500
    }
  })
} 